package com.yanqu.road.server.gameplayer.module.mogulbirthday;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.dao.impl.mogulbirthday.MogulBirthdayUserDataDaoImpl;
import com.yanqu.road.entity.banquet.invitation.BanquetCrossInvitation;
import com.yanqu.road.entity.enums.eBanquetInvitationType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.mogulbirthday.MogulBirthdayUserData;
import com.yanqu.road.pb.bossbirthday.MogulBirthdayProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MogulBirthdayModule extends GeneralModule {

    MogulBirthdayUserData userData;

    public MogulBirthdayModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        userData = new MogulBirthdayUserDataDaoImpl().getMogulBirthdayUserData(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        if(userData != null){
            if(userData.isInsertOption()){
                new MogulBirthdayUserDataDaoImpl().add(userData);
            }else if(userData.isUpdateOption()){
                new MogulBirthdayUserDataDaoImpl().update(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {

        if(!SystemOpenMgr.systemOpen(player, eSystemId.MogulBirthday.getValue())){
            return;
        }
        //重置
        dayReset();
    }

    public void syncUserData() {
        MogulBirthdayProto.CrossMogulBirthdaySyncData.Builder sync = MogulBirthdayProto.CrossMogulBirthdaySyncData.newBuilder();
        if(userData != null){
            MogulBirthdayProto.MogulBirthdayUserDataTemp.Builder builder = MogulBirthdayProto.MogulBirthdayUserDataTemp.newBuilder();
            builder.setGetReward(userData.isGetReward());
            sync.setUserData(builder);
            sync.addAllUserId(userData.getReadPostList());
        }
        player.sendPacket(Protocol.C_MOGUL_BIRTHDAY_SYNC_DATA, sync);
    }

    public synchronized void initUserData(){
        if(userData == null){
            userData = new MogulBirthdayUserData();
            userData.setUserId(player.getUserId());
            userData.setReadPostList(new ArrayList<>());
            userData.setDayResetTime(DateHelper.getTodayZeroTime());
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH, 0);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            userData.setResetTime(DateHelper.getZeroTime((int)(calendar.getTimeInMillis() / 1000)));
            userData.setInsertOption();
        }
    }

    public int userReward() {

        initUserData();

        if(userData.isGetReward()){
            return GameErrorCode.E_MOGUL_BIRTHDAY_USER_REWARD_GOT;
        }

        MogulBirthdayProto.CrossMogulBirthdayUserGetRewardReqMsg.Builder builder = MogulBirthdayProto.CrossMogulBirthdayUserGetRewardReqMsg.newBuilder();
        builder.setToday(DateHelper.getTodayZeroTime());
        player.sendPacket(Protocol.C_MOGUL_BIRTHDAY_USER_GET_REWARD, builder);
        return 0;


    }

    public int myRewardFromCross(String reward, long today, List<Long> serverIdList, long birthday) {
        if(userData.isGetReward()){
            return GameErrorCode.E_MOGUL_BIRTHDAY_USER_REWARD_GOT;
        }
        userData.setGetReward(true);
        userData.setBirthday(birthday);

        if(!StringUtils.isNullOrEmpty(reward)) {
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.MogulBirthday, eLogMoneyType.MogulBirthdayBirthdayReward);
        }

        //帖子
        BanquetCrossInvitation inv = new BanquetCrossInvitation();
        inv.setServerIdsStr(StringUtils.listToString(serverIdList, ","));
        player.getModule(BanquetModule.class).makeInvitation(eBanquetInvitationType.CrossBirthdayInvitation.getValue(), JSON.toJSONString(inv));
        MogulBirthdayProto.MogulBirthdayUserGetRewardRespMsg.Builder builder = MogulBirthdayProto.MogulBirthdayUserGetRewardRespMsg.newBuilder().setRet(0);
        builder.setReward(reward);
        MogulBirthdayProto.MogulBirthdayUserDataTemp.Builder buildUser = buildUser(userData);
        buildUser.setReward(reward);
        builder.setUserData(buildUser);
        player.sendPacket(Protocol.U_MOGUL_BIRTHDAY_USER_GET_REWARD, builder);
        return 0;
    }

    private MogulBirthdayProto.MogulBirthdayUserDataTemp.Builder buildUser(MogulBirthdayUserData userData) {
        MogulBirthdayProto.MogulBirthdayUserDataTemp.Builder builder = MogulBirthdayProto.MogulBirthdayUserDataTemp.newBuilder();
        builder.setGetReward(userData.isGetReward());
        builder.setReward("");
        builder.setBirthday(userData.getBirthday());
        return builder;
    }

    public int posterReward(long userId) {

        if(player.getUserId() == userId){
            return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
        }

        initUserData();

        if(userData.getReadPostList().contains(userId)){
            return GameErrorCode.E_MOGUL_BIRTHDAY_POSTER_REWARD_GOT;
        }

        MogulBirthdayProto.CrossMogulBirthdayPosterGetRewardReqMsg.Builder crossReq = MogulBirthdayProto.CrossMogulBirthdayPosterGetRewardReqMsg.newBuilder();
        crossReq.setUserId(userId);
        crossReq.setToday(DateHelper.getTodayZeroTime());
        player.sendPacket(Protocol.C_MOGUL_BIRTHDAY_POSTER_GET_REWARD, crossReq);
        return 0;
    }

    public int posterRewardFromCross(String reward, long mogulId) {

        if(userData.getReadPostList().contains(mogulId)){
            return GameErrorCode.E_MOGUL_BIRTHDAY_POSTER_REWARD_GOT;
        }
        userData.getReadPostList().add(mogulId);
        userData.setUpdateOption();
        if(!StringUtils.isNullOrEmpty(reward)){
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.MogulBirthday, eLogMoneyType.MogulBirthdayPosterReward);
        }

        MogulBirthdayProto.MogulBirthdayPosterGetRewardRespMsg.Builder respMsg = MogulBirthdayProto.MogulBirthdayPosterGetRewardRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setReward(reward);
        player.sendPacket(Protocol.U_MOGUL_BIRTHDAY_POSTER_GET_REWARD, respMsg);
        return 0;
    }

    public synchronized void dayReset(){
        if(userData != null){
            int zeroTime = DateHelper.getTodayZeroTime();
            if(userData.getDayResetTime() != zeroTime){
                userData.setDayResetTime(zeroTime);
                userData.setReadPostList(new ArrayList<>());
            }
            //year reset
            if(System.currentTimeMillis() / 1000 >= userData.getResetTime() + DateHelper.DAY_SECONDS * 365){
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.MONTH, 0);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                userData.setResetTime((int)(DateHelper.getZeroTimeStamp(calendar.getTimeInMillis()) / 1000));
            }
        }

        syncUserData();

        //清空道具(生辰宴)
        if(userData != null && userData.getBirthday() > 0){
            Calendar today = Calendar.getInstance();
            Calendar birthday = Calendar.getInstance();
            birthday.setTimeInMillis(userData.getBirthday() * 1000);
            if(getMonthDay(today) != getMonthDay(birthday)){
                player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty("110248=1"), eLogMoneyType.Banquet, eLogMoneyType.BanquetBirthdayOverTime);
            }
        }
    }

    public static int getMonthDay(Calendar calendar){
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int monthDay = Integer.valueOf(month + (day > 9 ? "": "0") + day);
        return monthDay;
    }
}
